package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.vo.PageResult;

import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public RecommendUser findMaxScoreUser(Long userId) {
        return mongoTemplate.findOne(new Query(Criteria.where("toUserid").is(userId)), RecommendUser.class);
    }

    @Override
    public PageResult recommendation(Long id, int page, int pagesize) {
        Criteria criteria = Criteria.where("toUserId").is(id);
        Query query = new Query(criteria)
                .with(Sort.by(Sort.Order.desc("score")))
                .with(PageRequest.of(page-1, pagesize));
        //分页查询列表
        List<RecommendUser> recommendUserList = mongoTemplate.find(query, RecommendUser.class);
        //查询数量
        long count = mongoTemplate.count(query, RecommendUser.class);
        //计算页数
        int pages = (int) Math.ceil(count * 1.0 / pagesize);
        //封装结果
        return new PageResult((int) count,pagesize,pages,page,recommendUserList);
    }

    @Override
    public RecommendUser findByIdSorce(Long userId, Long id) {

        Query query = new Query(Criteria.where("toUserId").is(userId).and("userId").is(id));
        return mongoTemplate.findOne(query, RecommendUser.class);
    }
}
